package com.skywolf.chem.manager;

import com.skywolf.chem.common.sysconfig.response.RespData;
import com.skywolf.chem.home.entity.LoopImg;
import com.skywolf.chem.home.service.ILoopImgService;
import com.skywolf.chem.live.entity.Live;
import com.skywolf.chem.live.entity.Video;
import com.skywolf.chem.live.service.ILiveService;
import com.skywolf.chem.live.service.IVideoService;
import com.skywolf.chem.tencent.utils.Signature;
import com.skywolf.chem.tencent.utils.TencentImgUtils;
import com.skywolf.chem.tencent.utils.UploadFileUtils;
import com.skywolf.chem.utils.SysConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.UUID;

/**
 * Created by pei_pei on 2020/12/7.
 */
@RestController
@RequestMapping("/manager/tencent")
@Api(value = "腾讯云文件服务类", description = "腾讯云文件服务类")
public class FileManagerController {
    Logger logger = LoggerFactory.getLogger(FileManagerController.class);

    @Autowired
    ILoopImgService loopImgService;

    @Autowired
    IVideoService videoService;

    @Autowired
    ILiveService liveService;

    @ApiOperation(value = "腾讯云点播获取签名",notes = "腾讯云点播获取签名")
    @RequestMapping(value = "/sign",method = {RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> sign(HttpServletRequest request) {
        String secretId = SysConfig._this.getProperty("tencent_cdn.secret_id");
        String secretKey = SysConfig._this.getProperty("tencent_cdn.secret_key");
        //得到Sign
        Signature sign = new Signature();
        //个人API密钥中的Secret Id
        sign.setSecretId(secretId);
        //个人API密钥中的Secret Key
        sign.setSecretKey(secretKey);
        sign.setCurrentTime(System.currentTimeMillis() / 1000);
        sign.setRandom(new Random().nextInt(Integer.MAX_VALUE));
        sign.setSignValidDuration(3600 * 24 * 2);
        String signature = null;
        try {
            signature = sign.getUploadSignature();
            System.out.println("signature : " + signature);
        } catch (Exception e) {
            System.out.print("获取签名失败");
            e.printStackTrace();
        }
        return RespData.success(signature);
    }


    /**
     * 上传文件轮播图
     * @throws BindException
     */
    @ResponseBody
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    private Object uploadImg(@RequestParam(value = "file") MultipartFile file,
                          HttpServletRequest request) {
        if (file == null) {
            return RespData.failResult("请选择上传文件");
        }
        try {
            String fileName = file.getOriginalFilename();
            Long time = System.currentTimeMillis();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String nameId = String.valueOf(time) + UUID.randomUUID() + suffix;

            String fileId = UploadFileUtils.uploadPicNew(file.getInputStream(), nameId, file.getContentType(), "edu_head");
            if (StringUtils.isBlank(fileId)) {
                return RespData.failResult("请选择上传文件");
            }
            String url = TencentImgUtils.domain + fileId;
            return RespData.success(url);
        } catch (Exception e) {
            logger.error("upload file fail,error message:{}", e.getMessage(), e);
        }
        return RespData.failResult("请选择上传文件");
    }

    /**
     * 上传文件轮播图
     * @throws BindException
     */
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    private Object upload(@RequestParam(value = "file") MultipartFile file,
                          @RequestParam(value = "id") Long id,
                          HttpServletRequest request) {
        if (file == null) {
            return RespData.failResult("请选择上传文件");
        }
        try {
            String fileName = file.getOriginalFilename();
            Long time = System.currentTimeMillis();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String nameId = String.valueOf(time) + UUID.randomUUID() + suffix;

            String fileId = UploadFileUtils.uploadPicNew(file.getInputStream(), nameId, file.getContentType(), "edu_head");
            if (StringUtils.isBlank(fileId)) {
                return RespData.failResult("请选择上传文件");
            }
            String url = TencentImgUtils.domain + fileId;
            LoopImg loopImg = new LoopImg();
            loopImg.setId(id);
            loopImg.setImgUrl(url);
            loopImg.setCreatedTime(LocalDateTime.now());
            loopImgService.updateById(loopImg);
            return RespData.success(url);
        } catch (Exception e) {
            logger.error("upload file fail,error message:{}", e.getMessage(), e);
        }
        return RespData.failResult("请选择上传文件");
    }

    @ApiOperation(value = "上传封面图")
    @ResponseBody
    @RequestMapping(value = "/uploadVideoImg",method = {RequestMethod.POST,RequestMethod.GET}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    private RespData<String> uploadVideoImg(@RequestParam MultipartFile file,
                                    @RequestParam(value = "id") Long id,
                                    HttpServletRequest request) {
        if (file == null) {
            return RespData.failResult("请选择上传文件");
        }
        try {
            String fileName = file.getOriginalFilename();
            Long time = System.currentTimeMillis();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String nameId = String.valueOf(time) + UUID.randomUUID() + suffix;

            String fileId = UploadFileUtils.uploadPicNew(file.getInputStream(), nameId, file.getContentType(), "edu_head");
            if (StringUtils.isBlank(fileId)) {
                return RespData.failResult("请选择上传文件");
            }
            String url = TencentImgUtils.domain + fileId;
            Video video = new Video();
            video.setId(id);
            video.setCoverImg(url);
            video.setUpdatedTime(LocalDateTime.now());
            videoService.updateById(video);
            return RespData.success(url);
        } catch (Exception e) {
            logger.error("upload file fail,error message:{}", e.getMessage(), e);
        }
        return RespData.failResult("请选择上传文件");
    }

    @ApiOperation(value = "上传直播封面图")
    @ResponseBody
    @RequestMapping(value = "/uploadLiveImg",method = {RequestMethod.POST,RequestMethod.GET}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    private RespData<String> uploadLiveImg(@RequestParam MultipartFile file,
                                            @RequestParam(value = "id") Long id,
                                            HttpServletRequest request) {
        if (file == null) {
            return RespData.failResult("请选择上传文件");
        }
        try {
            String fileName = file.getOriginalFilename();
            Long time = System.currentTimeMillis();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String nameId = String.valueOf(time) + UUID.randomUUID() + suffix;

            String fileId = UploadFileUtils.uploadPicNew(file.getInputStream(), nameId, file.getContentType(), "edu_head");
            if (StringUtils.isBlank(fileId)) {
                return RespData.failResult("请选择上传文件");
            }
            String url = TencentImgUtils.domain + fileId;
            Live live = new Live();
            live.setId(id);
            live.setCoverImg(url);
            live.setUpdatedTime(LocalDateTime.now());
            liveService.updateById(live);
            return RespData.success(url);
        } catch (Exception e) {
            logger.error("upload file fail,error message:{}", e.getMessage(), e);
        }
        return RespData.failResult("请选择上传文件");
    }
}
